import BaseModel from 'base/models/BaseModel.js';
import {
    ajax_call
} from 'tools.js';
import NodeFileModel from "../../common/models/NodeFileModel";


const FileRequirementModel = BaseModel.extend({
    itemBaseUrl: "/api/v1/indicators/",
    label() {
        let status = this.get('status');
        let requirement_type = this.get('requirement_type');
        let file_id = this.get('file_id');
        let validation_status = this.get('validation_status');
        let forced = this.get('forced');
        let file_type = this.get('file_type');

        var label = file_type.label;
        if (status == 'danger') {
            label += ": <b>Aucun fichier n'a été fourni</b>";
        } else if (status == 'warning') {
            if (requirement_type == 'recommended') {
                label += " (recommandé)";
            } else if (validation_status != 'valid') {
                label += ": <b>Fichier en attente de validation</b>";
            }
        } else if (forced) {
            label += "La validation a été forcée";
        }
        return label;
    },
    missingFile() {
        let status = this.get('status');
        return ((status != 'success') && (!this.has('file_id')))
    },
    hasFile() {
        return this.has('file_id');
    },
    get(attribute) {
        let v = FileRequirementModel.__super__.get.apply(this, arguments);
        // BB does not handle nested models natively ; thus we rehydrate it by hand.
        if (attribute === 'file_object') {
            v = new NodeFileModel(v);
        }
        return v
    },
    setValid() {
        const url = this.itemBaseUrl + this.get('id') + '?action=validation_status';
        var serverRequest = ajax_call(url, {
                "validation_status": "valid"
            },
            "PUT"
        );
        return serverRequest.then(this.fetch.bind(this));
    },
    error(message) {
        return {
            'file_requirements': message
        };
    },
    validate(validation_status) {
        let result = true;
        if (this.get('requirement_type') == 'optionnal') {
            return result;
        }
        if (this.get('status') != 'success') {
            if (this.missingFile()) {
                result = false;
            } else if (validation_status == 'valid') {
                result = false;
            }
        }
        return result;
    }
});
export default FileRequirementModel;